import { defineStore } from 'pinia';
import { DialogueInfoStates } from '../interface';

/*
 * chat 模块数据 
 */
export const useDialogueInfo = defineStore('dialogueInfo', {
    state: (): DialogueInfoStates => ({
        talk_type: 0, // 对话来源[1:私聊;2:群聊]
        receiver_id: 0, // 接收者ID
        is_robot: 0,
        records: [], // 聊天记录
        index_name: null, // 对话索引（聊天对话的唯一索引）
    }),
    actions: {
        // 更新对话
        UPDATE_DIALOGUE_MESSAGE(resource: any) {
            this.records = []
            this.talk_type = parseInt(resource.talk_type)
            this.receiver_id = parseInt(resource.receiver_id)
            this.is_robot = parseInt(resource.is_robot)

            if (this.talk_type === 0 || this.receiver_id === 0) {
                this.index_name = null
            } else {
                this.index_name = resource.talk_type + '_' + resource.receiver_id
            }
        },
        // 数组头部压入对话记录
        UNSHIFT_DIALOGUE(records: any) {
            this.records.unshift(...records)
        },
        // 推送对话记录
        PUSH_DIALOGUE(record: any) {
            this.records.push(record)
        },
        // 更新对话记录
        UPDATE_DIALOGUE(resource: any) {
            for (const iterator of this.records) {
              if (iterator.id === resource.id) {
                Object.assign(iterator, resource)
                break
              }
            }
        },
        // 删除对话记录
        DELETE_DIALOGUE(index: number) {
            this.records.splice(index, 1)
        },

        BATCH_DELETE_DIALOGUE(ids: Array<string>) {
            ids.forEach(record_id => {
              let index = this.records.findIndex(item => item.id == record_id)
              if (index >= 0) this.records.splice(index, 1)
            })
        },
        // 数组头部压入对话记录
        SET_DIALOGUE(records: any) {
            this.records = records
        }
    }
})